<template>
  <div class="container">
    <van-nav-bar
      fixed
      title="注册账号"
      @click-left="$router.back()"
      left-arrow
    />

    <div class="logo-txt">欢迎注册</div>
    <van-form @submit="onSubmit" label-width="70px">
      <van-field
        v-model="username"
        name="mobile"
        label="用户名"
        placeholder="请输入手机号"
        left-icon="manager"
        :rules="[
          { required: true, message: '请填写用户名' },
          { pattern: /^(?:(?:\+|00)86)?1\d{10}$/, message: '手机号格式不正确' },
        ]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        left-icon="lock"
        :rules="[
          { required: true, message: '请填写密码' },
          { pattern: /^\w{6,}$/, message: '密码至少包含6个字符' },
        ]"
      />
      <van-field
        v-model="twopassword"
        type="password"
        name="twopassword"
        label="确认密码"
        placeholder="确认密码"
        left-icon="lock"
        :rules="[
          { required: true, message: '请填写密码' },
          { pattern: /^\w{6,}$/, message: '密码至少包含6个字符' },
          {
            validator: pattern,
            message: '两次输入密码不一致',
          },
        ]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >立即注册</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import Vue from "vue";
import { Toast } from "vant";

Vue.use(Toast);
// 导入封装 的API 函数
import { regApi } from "@/api/user";
export default {
  data() {
    return {
      username: "",
      password: "",
      twopassword: "",
    };
  },
  methods: {
    pattern() {
      if (this.password !== this.twopassword) {
        return false;
      }
    },
    async onSubmit(values) {
      // console.log("submit", values);
      const res = await regApi(values);
      const {  errno } = res;
      // localStorage.setItem("token", data.token);
      if (errno === 0) {
        Toast.loading({
          duration: 0, // 持续展示 toast
          forbidClick: true,
          message: "注册成功 跳转登录",
        });
        let second = 2;
        const timer = setInterval(() => {
          second--;
          if (second) {
            // Toast.message = ` ${second} 秒跳转登录`;
          } else {
            clearInterval(timer);
            // 手动清除 Toast
            Toast.clear();
            this.$router.replace("/login")
          }
        }, 1000);
      }
    },
  },
};
</script>

<style scoped>
.logo-txt {
  text-align: center;
  font-size: 60px;
  margin: 60px auto;
  color: #1989fa;
}
</style>
